package com.topisv.tms.web;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.BatchTask;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.TaskNumber;
import com.topisv.tms.entity.User;
import com.topisv.tms.service.BatchTaskService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.TaskNumberService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.date.TopIsvDateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

import net.sf.json.JSONObject;

/**
 * 拣货批次管理
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping(value = "/batchTask")
public class BatchTaskController {
	private static final Logger log = LoggerFactory.getLogger(BatchTaskController.class);
	
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private BatchTaskService batchTaskService;
	@Autowired
	private TaskNumberService taskNumberService;
	@Autowired
	private CustomersService customersService;

	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private ShopSourceService shopSourceService;
	

	private List<EdiOrder> getEdiOrderNew(Map<String, Object> searchParams)
			throws Exception {
		Date fromDate = null;
		Date endDate = null;
		String areaListsAreaGroupCode = null;
		List<EdiOrder> ediOrdersPages = null;
		String areaLists = "";
		try {
			areaListsAreaGroupCode = (String) searchParams.get("areaLists");
			searchParams.remove("areaLists");
			String from = (String) searchParams.get("fromDate");
			String end = (String) searchParams.get("endDate");
            String shopCode=(String)searchParams.get("EQ_shopCode");
            if("-1".equals(shopCode)){
            	searchParams.remove("EQ_shopCode");
            }
			searchParams.remove("fromDate");
			searchParams.remove("endDate");

			if (from.length() > 10) {
				fromDate = TimeUtil.getDateMMSS(from);
			} else {
				fromDate = TimeUtil.getDate(from);
			}
			if (end.length() > 10) {
				endDate = TimeUtil.getDateMMSS(end);
			} else {
				endDate = TimeUtil.getDate(end);
			}
			fromDate = TopIsvDateUtils.addHours(fromDate, -14);
			endDate = TopIsvDateUtils.addHours(endDate, -14);
			searchParams.put("EQ_orderStatus", "ok");
			searchParams.put("EQ_status", "pending");
			searchParams.put("EQ_gymemo", "1");
			ediOrdersPages = ediOrderService.crTimeHoursLists(fromDate.toString(), endDate.toString(), searchParams);
			areaLists = areaListsAreaGroupCode.split("--")[0];
			ediOrdersPages = getEdiOrders(ediOrdersPages, areaLists);

			searchParams.put("fromDate", from);
			searchParams.put("endDate", end);
			searchParams.put("areaLists", areaListsAreaGroupCode);
		} catch (Exception e) {
			throw e;
		}
		return ediOrdersPages;
	}

	@RequestMapping(value = "searchNew")
	public String searchNw(
			@RequestParam(value = "sortType", defaultValue = "adtime_desc") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request, ServletResponse response)
			throws Exception {
		List<EdiOrder> ediOrdersPages = null;
		List<EdiOrder> tempEdiOrdersPages = new ArrayList<EdiOrder>();
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");;
		String type = "single";
		ShiroUser user = getShiroUser();
		RestCustomersAreagroupVo restCustomersAreagroupVo = null;
		String customerCode =(String) searchParams.get("EQ_customerCode");
		TaskNumber taskNumber = null;
		String message = "";
		ediOrdersPages = getEdiOrderNew(searchParams);// 获得订单信息
		String areaListsAreaGroupCode = (String) searchParams.get("areaLists");
		Customers customersOne=null;
		List<Customers> customers=null;
		
		taskNumber = taskNumberService.findByTypeAndCustomerCode(type,customerCode);
		
		try {
			 customers = customersService.loadCustomerByAuthority(user);
			 customersOne=customersService.findByCustomerCode(customerCode);
			 if("1".equals(customersOne.getSectionPo())){
					model.addAttribute("isdelv", "1");
			 }else{
					model.addAttribute("isdelv", "0");
			 }
			  try {
					restCustomersAreagroupVo =customerAreaGroupService.getRestCustomersAreagroupVo(customerCode);// HttpPost.getRestCustomersAreagroupVo(customersOne);// 设置网点信息
				} catch (Exception e) {
					log.error("/batchTask/searchNew" + e);
					
				}
			//setOrderType(ediOrdersPages, tempEdiOrdersPages, type);// 设置订单的类型单件，多件,查看订单明细是否存在
			  if("0".equals(customersOne.getPlaceStatus())){
				  if("1".equals(customersOne.getSectionPo())){
						//batchTaskService.countOrdenos(ediOrdersPages,customerCode, restCustomersAreagroupVo.getRestAreaGroupDtos().get(0).getAreagroupCode());
				  }else{
						batchTaskService.countOrdenos(ediOrdersPages);
				  }
			  } 
			setModel(model,ediOrdersPages);
		} catch (Exception e) {
			
			message += e.getMessage();
			log.error("/batchTask/initNew" + e);
		}
		List<ShopSource> shopSources=shopSourceService.findByCustomerCode(customerCode);
		model.addAttribute("shopSources", shopSources);//店铺
		model.addAttribute("ordenoSourceCode", searchParams.get("EQ_erpType"));
		List<OrdenoSource> ordenoSources=customersService.findOrdenoSource(customerCode);//订单来源平台
		model.addAttribute("ordenoSources", ordenoSources);
		model.addAttribute("customers", customers);
		model.addAttribute("object", restCustomersAreagroupVo);
		model.addAttribute("ediOrders", tempEdiOrdersPages);
		model.addAttribute("provice",((String) searchParams.get("areaLists")).split("--")[0]);
		model.addAttribute("areaCode", searchParams.get("areaLists"));
		model.addAttribute("customerCode", customerCode);
		model.addAttribute("message", tempEdiOrdersPages.size() + "<br>"+ message);
		model.addAttribute("provice",areaListsAreaGroupCode.split("--")[0]);
		model.addAttribute("type", type);
		model.addAttribute("taskNumber", taskNumber);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

		return "batchTask/createBatchTasksNew";
	}

	private void setModel(Model model,List<EdiOrder> ediOrders) throws Exception {
		try {
			
			model.addAttribute("message", ediOrders.size());
			List<EdiOrder> singleEdiOrders = new ArrayList<EdiOrder>();
			List<EdiOrder> multipleEdiOrders = new ArrayList<EdiOrder>();
			List<EdiOrder> forwardEdiOrders = new ArrayList<EdiOrder>();
			setOrderType(ediOrders, singleEdiOrders, "single");// 设置订单的类型单件，多件,查看订单明细是否存在
			setOrderType(ediOrders, multipleEdiOrders, "multiple");// 设置订单的类型单件，多件,查看订单明细是否存在
			setOrderType(ediOrders, forwardEdiOrders, "forward");// 设置订单的类型单件，多件,查看订单明细是否存在
			model.addAttribute("singleEdiOrders", singleEdiOrders);
			model.addAttribute("multipleEdiOrders", multipleEdiOrders);
			model.addAttribute("forwardEdiOrders", forwardEdiOrders);
		} catch (Exception e) {
			throw e;
		}

	}

	@RequestMapping(value = "initNew")
	public String initNew(Model model) {
		ShiroUser user = getShiroUser();
		List<Customers> customerLists=null;
		Customers customersOne=null;
		try {
			customerLists=customersService.loadCustomerByAuthority(user);//获得商家信息
			customersOne=customerLists.get(0);
			if("1".equals(customersOne.getSectionPo())){
				model.addAttribute("isdelv", "1");
			}else{
				model.addAttribute("isdelv", "0");
			}
			String customerCode = customersOne.getCustomerCode();
			List<OrdenoSource> ordenoSources=customersService.findOrdenoSource(customerCode);//订单来源平台
			RestCustomersAreagroupVo restCustomersAreagroupVo = null;
			try {
				restCustomersAreagroupVo = customerAreaGroupService.getRestCustomersAreagroupVo(customerCode);//HttpPost.getRestCustomersAreagroupVo(customersOne);
			} catch (Exception e) {
				
			}
			List<EdiOrder> ediOrders = ediOrdenos(customerCode,ordenoSources.get(0).getOrdenoSourceCode());
			ediOrders = getEdiOrders(ediOrders, restCustomersAreagroupVo.getRestAreaGroupDtos().get(0).getAreaCodes());
			
			if("0".equals(customersOne.getPlaceStatus())){
				  if("1".equals(customersOne.getSectionPo())){
						//batchTaskService.countOrdenos(ediOrders,customerCode, restCustomersAreagroupVo.getRestAreaGroupDtos().get(0).getAreagroupCode());
				  }else{
						batchTaskService.countOrdenos(ediOrders);
				  }
			} 
			
			model.addAttribute("message", ediOrders.size());
			List<EdiOrder> singleEdiOrders = new ArrayList<EdiOrder>();
			List<EdiOrder> multipleEdiOrders = new ArrayList<EdiOrder>();
			List<EdiOrder> forwardEdiOrders = new ArrayList<EdiOrder>();
			setOrderType(ediOrders, singleEdiOrders, "single");// 设置订单的类型单件，多件,查看订单明细是否存在
			setOrderType(ediOrders, multipleEdiOrders, "multiple");// 设置订单的类型单件，多件,查看订单明细是否存在
			setOrderType(ediOrders, forwardEdiOrders, "forward");// 设置订单的类型单件，多件,查看订单明细是否存在

			TaskNumber singleTaskNumber = taskNumberService.findByTypeAndCustomerCode("single", customerCode);
			TaskNumber multipleTaskNumber = taskNumberService.findByTypeAndCustomerCode("multiple", customerCode);
			TaskNumber forwardTaskNumber = taskNumberService.findByTypeAndCustomerCode("forward", customerCode);
			List<ShopSource> shopSources=shopSourceService.findByCustomerCode(customerCode);
			model.addAttribute("shopSources", shopSources);//店铺
			model.addAttribute("singleTaskNumber", singleTaskNumber);
			model.addAttribute("multipleTaskNumber", multipleTaskNumber);
			model.addAttribute("forwardTaskNumber", forwardTaskNumber);

			model.addAttribute("taskNumber", multipleTaskNumber);
			model.addAttribute("object", restCustomersAreagroupVo);
            model.addAttribute("customerCode", customerCode);
			model.addAttribute("customers", customerLists);
			
			model.addAttribute("ordenoSources", ordenoSources);
			model.addAttribute("ordenoSourceCode", ordenoSources.get(0).getOrdenoSourceCode());
			model.addAttribute("singleEdiOrders", singleEdiOrders);
			model.addAttribute("multipleEdiOrders", multipleEdiOrders);
			model.addAttribute("forwardEdiOrders", forwardEdiOrders);
		} catch (Exception e) {
			log.error("/batchTask/init" + e);
			
		}
		return "batchTask/createBatchTasksNew";
	}

	private List<EdiOrder> ediOrdenos(String customerCode,String erpType) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		try {
			searchParams.put("EQ_orderStatus", "ok");
			searchParams.put("EQ_status", "pending");
			searchParams.put("EQ_gymemo", "1");
			searchParams.put("EQ_erpType", erpType);
			searchParams.put("EQ_customerCode", customerCode);
			List<EdiOrder> ediOrders = ediOrderService.crTimeHoursLists(searchParams);
			return ediOrders;
		} catch (Exception e) {
			throw e;
		}
	}


	

	private void setOrderType(List<EdiOrder> ediOrders,
			List<EdiOrder> tempEdiOrders, String type) throws Exception {
		StringBuffer orderItems = new StringBuffer();
		try {
			for (EdiOrder e : ediOrders) {
				// 设置订单的单件与多件
				if (e.getOrderType() == null || "".equals(e.getOrderType())) {
					List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(e.getCustomerCode(), e.getOrdeno());
					if (ediOrderItems.isEmpty()) {
						if ("".equals(orderItems.toString())) {
							orderItems.append(e.getOrdeno());
						} else {
							orderItems.append(":" + e.getOrdeno());
						}
						continue;
					}
					if (ediOrderItems.size() > 1) {
						e.setOrderType("multiple");

					} else if (ediOrderItems.get(0).getQty() > 1) {
						e.setOrderType("multiple");

					} else {
						e.setOrderType("single");

					}
					if (!"forward".equals(e.getForwardSign())) {
						e.setForwardSign(e.getOrderType());
					}
					ediOrderService.save(e);
				}

				// 中转发的订单不区分单件多件
				if ("forward".equals(type)
						&& "forward".equals(e.getForwardSign())) {
					tempEdiOrders.add(e);
					continue;
				}
				if (type.equals(e.getOrderType())
						&& !"forward".equals(e.getForwardSign())) {
					tempEdiOrders.add(e);
				}
			}
			if (!"".equals(orderItems.toString())) {
				throw new Exception("订单号:" + orderItems.toString() + "商品明细不存在");
			}
		} catch (Exception e) {
			throw e;
		}
	}

	private List<EdiOrder> getEdiOrder(String customerCode, String ordenos)
			throws Exception {
		List<EdiOrder> ediOrdersPages = new ArrayList<EdiOrder>();

		try {
			String[] ordenoLists = ordenos.split(":");
			for (String o : ordenoLists) {
				//ediOrdersPages.add(ediOrderService.findByCustomerCodeAndOrdeno(customerCode, o));
				ediOrdersPages.add(ediOrderService.findByOrdeno(o));
			}
		} catch (Exception e) {
			throw e;
		}
		return ediOrdersPages;
	}



	/**
	 * 生成拣货任务
	 * 
	 * @param ordenos
	 * @param orderType
	 * @param customerCode
	 * @param number
	 * @param erpType
	 * @param response
	 */
	@RequestMapping(value = "ajaxOrdenosCreateBatchTask")
	public void ajaxOrdenosCreateBatchTask(
			@RequestParam(value = "ordenos") String ordenos,
			@RequestParam(value = "orderType") String orderType,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "number", defaultValue = "1000") int number,
			@RequestParam(value = "areaLists") String areaLists,
			@RequestParam(value = "isdelv") String isdelv,
			@RequestParam(value = "ordenoSourceCode") String ordenoSourceCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();
		List<EdiOrder> ediOrdersDelvYes = null;
		List<EdiOrder> ediOrdersDelvNo = null;
		List<BatchTask> allBatchTasks = null;
		Customers customers = null;
		try {
			log.info("开始生成分拣批次");
			log.info("ordenos="+ordenos);
			log.info("orderType="+orderType);
			log.info("customerCode="+customerCode);
			log.info("number="+number);
			log.info("areaLists="+areaLists);
			log.info("isdelv="+isdelv);
			log.info("ordenoSourceCode="+ordenoSourceCode);
			json = new JSONObject();
			out = response.getWriter();
			customers = customersService.findByCustomerCode(customerCode);
			List<EdiOrder> ediOrdersPages = getEdiOrder(customerCode,ordenos);
			if (ediOrdersPages.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "没有订单");
				out.print(json.toString());
				return;
			}
			// 生成分仓订单批次
			if ("1".equals(isdelv) || "1".equals(customers.getSectionPo())) {
				ediOrdersDelvYes = new ArrayList<EdiOrder>();
				ediOrdersDelvNo = new ArrayList<EdiOrder>();
				setIsdelvOrdeno(ediOrdersPages, ediOrdersDelvYes,ediOrdersDelvNo);
				List<BatchTask> batchTasks = batchTaskService.createBatchTask(
						ediOrdersDelvYes, user.jobuuid, orderType,
						customerCode, number, areaLists,
						StatusEnums.ZWAREHOUSE.getStatus(),ordenoSourceCode);

				allBatchTasks = batchTaskService.createBatchTask(
						ediOrdersDelvNo, user.jobuuid, orderType, customerCode,
						number, areaLists,
						StatusEnums.FWAREHOUSE.getStatus(),ordenoSourceCode);
				allBatchTasks.addAll(batchTasks);

			} else {
				allBatchTasks = batchTaskService.createBatchTask(
						ediOrdersPages, user.jobuuid, orderType, customerCode,
						number, areaLists, 
						StatusEnums.ZWAREHOUSE.getStatus(),ordenoSourceCode);
			}

			if (allBatchTasks.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "生成拣货任务批次错误");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", allBatchTasks.size());
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 得出分仓订单与总仓订单
	 * 
	 * @param ediOrdersPages
	 * @param ediOrdersDelvYes
	 * @param ediOrdersDelvNo
	 */
	private void setIsdelvOrdeno(List<EdiOrder> ediOrdersPages,
			List<EdiOrder> ediOrdersDelvYes, List<EdiOrder> ediOrdersDelvNo) {
		for (EdiOrder e : ediOrdersPages) {
			if (e.getIsdelv()) {
				ediOrdersDelvYes.add(e);
			} else {
				ediOrdersDelvNo.add(e);
			}
		}
	}

	
	@RequestMapping(value = "batchTaskLists/{from}")
	public String batchTaskDate(@PathVariable("from") String from, Model model) {
		Date startDate = null;
		Date endDate = null;
		List<BatchTask> batchTasks = null;
		ShiroUser shiroUser = getShiroUser();
		try {
			startDate = TimeUtil.getDate(from);
			endDate = TopIsvDateUtils.addDays(startDate, 1);
			batchTasks = batchTaskService.findByCreateDateBetween(startDate,endDate);

			
			if(StatusEnums.user_type_paiu.getStatus().equals(shiroUser.userType)){//派友用户
				batchTasks=getBatchTasks(batchTasks,shiroUser.customers, shiroUser.areagroups);
			}else if(StatusEnums.user_type_customer.getStatus().equals(shiroUser.userType)){//商家用户
				batchTasks = getBatchTasks(batchTasks, shiroUser.customerCode);

			}
			
			
			for (BatchTask batchTask : batchTasks) {
				User user = accountService.findUserByJobuuid(batchTask.getJobuuid());
				TaskNumber taskNumber = taskNumberService.findByTypeAndCustomerCode(batchTask.getType(),batchTask.getCustomerCode());
				batchTask.setBackupTaskNumber(taskNumber.getBackupTaskNumber());
				batchTask.setUsername(user.getRealname());
			}
			model.addAttribute("object", batchTasks);
			model.addAttribute("from", from);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return "batchTask/batchTaskLists";
	}
	
	private List<BatchTask> getBatchTasks(List<BatchTask> batchTasks,String customers,String areagroups) throws Exception {
		try {
			List<BatchTask> tempBatchTasks = new ArrayList<BatchTask>();
			for (BatchTask b : batchTasks) {
				if (customers.indexOf(b.getCustomerCode())>-1) {
					tempBatchTasks.add(b);
				}else if(areagroups.indexOf(b.getAreaGroupCode())>-1){
					tempBatchTasks.add(b);
				}
			}
			return tempBatchTasks;
		} catch (Exception e) {
			throw e;
		}
	}

	private List<BatchTask> getBatchTasks(List<BatchTask> batchTasks,String customerCode) throws Exception {
		try {
			List<BatchTask> tempBatchTasks = new ArrayList<BatchTask>();
			for (BatchTask b : batchTasks) {
				if (customerCode.equals(b.getCustomerCode())) {
					tempBatchTasks.add(b);
				}
			}
			return tempBatchTasks;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 显示未处理的拣货任务
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "batchTaskLists")
	public String batchTask(Model model) {
		String status = "pending";// 未处理的拣货任务
		ShiroUser user = getShiroUser();
		List<BatchTask> batchTasks = null;
		try {
			if(StatusEnums.user_type_paiu.getStatus().equals(user.userType)){
				batchTasks=batchTaskService.findBatchTaskStatus(user.customers, user.areagroups, status);
			}else if(StatusEnums.user_type_customer.getStatus().equals(user.userType)){//商家用户
				batchTasks=batchTaskService.findByStatusAndCustomerCode(status, user.customerCode);
			}
			
			if(batchTasks!=null){
				for (BatchTask batchTask : batchTasks) {
					User u = accountService.findUserByJobuuid(batchTask.getJobuuid());
					batchTask.setUsername(u.getRealname());
					String type = batchTask.getType();

					TaskNumber taskNumber = taskNumberService.findByTypeAndCustomerCode(type, batchTask.getCustomerCode());
					batchTask.setBackupTaskNumber(taskNumber.getBackupTaskNumber());
				}
			}
			
			model.addAttribute("object", batchTasks);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return "batchTask/batchTaskLists";
	}

	private List<EdiOrder> getEdiOrders(List<EdiOrder> ediOrdersPages,
			String areaLists) {
		List<EdiOrder> ediOrders = new ArrayList<EdiOrder>();
		for (EdiOrder ediOrdersPage : ediOrdersPages) {
			String provco = ediOrdersPage.getProvco();
			try {
				if (findProvco(provco, areaLists)) {
					ediOrders.add(ediOrdersPage);
				}
			} catch (Exception e) {
				
			}
			
		}
		return ediOrders;
	}

	private boolean findProvco(String provco, String areaLists) {
		String[] lists = areaLists.split(",");
		for (String list : lists) {
			if (provco.equals(list)) {
				return true;
			}
		}
		return false;
	}

	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
}
